package com.admin_system.service.impl;

import com.admin_system.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件服务实现类
 * 使用Spring Mail和Thymeleaf实现邮件发送功能
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired(required = false)
    private TemplateEngine templateEngine;
    
    @Value("${spring.mail.username:system@example.com}")
    private String fromEmail;
    
    @Value("${app.name:数智作业管理系统}")
    private String appName;

    /**
     * 异步发送验证码邮件
     * 
     * @param email 接收者邮箱地址
     * @param code 验证码
     * @return 发送成功返回true，失败返回false
     */
    @Async
    @Override
    public boolean sendVerificationCode(String email, String code) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail);
            helper.setTo(email);
            helper.setSubject(appName + " - 找回密码验证码");
            
            String content;
            
            // 如果配置了Thymeleaf，使用模板发送邮件
            if (templateEngine != null) {
                Context context = new Context();
                context.setVariable("code", code);
                context.setVariable("appName", appName);
                content = templateEngine.process("mail/verification-code", context);
            } else {
                // 否则使用简单的HTML
                content = getSimpleVerificationEmailTemplate(code);
            }
            
            helper.setText(content, true);
            
            mailSender.send(message);
            logger.info("验证码邮件发送成功: {}", email);
            
            return true;
        } catch (Exception e) {
            logger.error("发送验证码邮件失败", e);
            return false;
        }
    }

    /**
     * 异步发送密码重置成功通知邮件
     * 
     * @param email 接收者邮箱地址
     * @return 发送成功返回true，失败返回false
     */
    @Async
    @Override
    public boolean sendPasswordResetNotification(String email) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail);
            helper.setTo(email);
            helper.setSubject(appName + " - 密码重置成功");
            
            String content;
            
            // 如果配置了Thymeleaf，使用模板发送邮件
            if (templateEngine != null) {
                Context context = new Context();
                context.setVariable("appName", appName);
                content = templateEngine.process("mail/password-reset-success", context);
            } else {
                // 否则使用简单的HTML
                content = getSimpleResetSuccessEmailTemplate();
            }
            
            helper.setText(content, true);
            
            mailSender.send(message);
            logger.info("密码重置成功邮件发送成功: {}", email);
            
            return true;
        } catch (Exception e) {
            logger.error("发送密码重置成功邮件失败", e);
            return false;
        }
    }
    
    /**
     * 获取简单的验证码邮件模板
     * 
     * @param code 验证码
     * @return HTML格式的邮件内容
     */
    private String getSimpleVerificationEmailTemplate(String code) {
        return "<!DOCTYPE html>"
                + "<html>"
                + "<head>"
                + "<meta charset=\"UTF-8\">"
                + "<title>验证码</title>"
                + "<style>"
                + "body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px; }"
                + ".container { border: 1px solid #ddd; border-radius: 5px; padding: 20px; }"
                + ".header { text-align: center; margin-bottom: 20px; }"
                + ".code-container { background-color: #f5f5f5; padding: 10px; text-align: center; border-radius: 5px; margin: 20px 0; }"
                + ".code { font-size: 24px; font-weight: bold; letter-spacing: 5px; color: #3b82f6; }"
                + ".footer { font-size: 12px; color: #999; margin-top: 20px; text-align: center; }"
                + "</style>"
                + "</head>"
                + "<body>"
                + "<div class=\"container\">"
                + "<div class=\"header\">"
                + "<h2>" + appName + " - 找回密码验证码</h2>"
                + "</div>"
                + "<p>您好，</p>"
                + "<p>您正在进行密码找回操作，请使用以下验证码完成验证：</p>"
                + "<div class=\"code-container\">"
                + "<div class=\"code\">" + code + "</div>"
                + "</div>"
                + "<p>验证码有效期为10分钟，请勿将验证码泄露给他人。</p>"
                + "<p>如果不是您本人操作，请忽略此邮件。</p>"
                + "<div class=\"footer\">"
                + "<p>此邮件由系统自动发送，请勿回复。</p>"
                + "<p>&copy; " + java.time.Year.now().getValue() + " " + appName + "</p>"
                + "</div>"
                + "</div>"
                + "</body>"
                + "</html>";
    }
    
    /**
     * 获取简单的密码重置成功邮件模板
     * 
     * @return HTML格式的邮件内容
     */
    private String getSimpleResetSuccessEmailTemplate() {
        return "<!DOCTYPE html>"
                + "<html>"
                + "<head>"
                + "<meta charset=\"UTF-8\">"
                + "<title>密码重置成功</title>"
                + "<style>"
                + "body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px; }"
                + ".container { border: 1px solid #ddd; border-radius: 5px; padding: 20px; }"
                + ".header { text-align: center; margin-bottom: 20px; }"
                + ".success-icon { font-size: 48px; color: #10b981; text-align: center; margin: 20px 0; }"
                + ".footer { font-size: 12px; color: #999; margin-top: 20px; text-align: center; }"
                + "</style>"
                + "</head>"
                + "<body>"
                + "<div class=\"container\">"
                + "<div class=\"header\">"
                + "<h2>" + appName + " - 密码重置成功</h2>"
                + "</div>"
                + "<p>您好，</p>"
                + "<p>您的账户密码已成功重置。</p>"
                + "<div class=\"success-icon\">✓</div>"
                + "<p>如果不是您本人操作，请立即联系管理员或者再次重置密码。</p>"
                + "<div class=\"footer\">"
                + "<p>此邮件由系统自动发送，请勿回复。</p>"
                + "<p>&copy; " + java.time.Year.now().getValue() + " " + appName + "</p>"
                + "</div>"
                + "</div>"
                + "</body>"
                + "</html>";
    }
} 